<template>
  <div class="tem_page">
    <el-card class="card-title">
      <div slot="header" class="action_line">
        <span>线索商品-新增</span>
        <div class="operating-area">
          <span v-if="isSubmit">
            <el-button type="primary" @click="hanldeGoBack">保持下架状态</el-button>
            <el-button  type="primary" :loading="submitBtnLoading" @click="batchPutOnShelves">立即上架</el-button>
          </span>
          <span v-else>
            <el-button type="primary" :loading="saveBtnLoading" @click="handleSaveAction">保存</el-button>
            <el-button type="primary" :loading="submitBtnLoading" @click="handleSubmit">提交</el-button>
            <el-button @click="hanldeGoBack">返回</el-button>
          </span>
        </div>
      </div>
      <el-form
        ref="tempForm"
        :model="formData"
        label-width="135px"
        style="width: 80%"
        :inline="false"
        :disabled="isSubmit"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="售卖平台："
              prop="salePlats"
              :rules="[{ required: true, message: '售卖平台不能为空', trigger: 'change'}]"
            >
              <el-select
                class="width100"
                v-model="formData.salePlats"
                multiple
                placeholder="若线上展示需勾选对应平台"
              >
                <el-option
                  v-for="item in salesPlatformList"
                  :key="item.salePlatCode"
                  :label="item.salePlatName"
                  :value="item.salePlatCode">
                </el-option>
              </el-select>
              <span class="tip">若线上展示需勾选对应平台</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="销售区域："
              prop="saleAreasName"
              :rules="[
              {
                required: saleAreasIsRequired,
                message: '销售区域不能为空',
                trigger: 'change'
              }]"
            >
              <el-input
                class="sale-area-input"
                placeholder="请选择销售区域"
                v-model="formData.saleAreasName"
                @focus="handleShowCityDialog"
              >
                <el-button slot="append" icon="el-icon-search" @click="handleShowCityDialog" />
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="下架类型：" :required="true">
              <el-select
                v-model="formData.offTimeType"
                :disabled="isFromSourcing"
                placeholder="请选择下架类型"
                @change="handleOffTimeTypeSelect"
              >
                <el-option
                  v-for="item in OFFTIME_TYPE_OPTIONS"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自定义商品名称：" :required="true">
              <el-select v-model="formData.productNameType" placeholder="请选择" @change="handleProductNameTypeSelect">
                <el-option
                  v-for="item in PRODUCT_NAME_TYPE"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="formData.offTimeType == 1">
            <el-form-item label="预计下架日期：" prop="expectOffTime" :rules="[{ required: formData.offTimeType == 1, message: '预计下架日期不能为空', trigger: 'change'}]">
              <el-date-picker
                v-model="formData.expectOffTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="action_line">
        <span>线索商品列表</span>
        <div class="operating-area" v-if="!isSubmit">
          <el-button @click="addButton" v-if="addTemporaryFlag">添加</el-button>
          <el-button @click="concatDialog(1, 0)">关联品类</el-button>
          <el-button @click="concatDialog(1, 2)">关联品牌</el-button>
          <el-button @click="concatDialog(1, 5)">材质</el-button>
          <el-button @click="concatDialog(1, 'series')">系列</el-button>
          <el-button @click="handleCheckSameBrand">一键勾选相同品牌</el-button>
          <el-button @click="handleCheckSameCategory">一键勾选相同分类</el-button>
          <el-button @click="concatDialog(1, 9)">归类名称</el-button>
          <el-button v-if="!isFromSourcing" @click="concatDialog(1, 3)">关联单位</el-button>
          <el-button :loading="btnLoadings.export" @click="handleExportTemplate">导出模板</el-button>
          <el-upload
            class="import-file"
            ref="bacthUpload"
            :action="`${uploadBaseURL}sysback/product/collect/importSkuDetail`"
            accept=".xls, .xlsx"
            :before-upload="beforeFileUpload"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :show-file-list="false"
            :data="uploadData"
          >
            <el-button :loading="btnLoadings.import">导入模板</el-button>
          </el-upload>
        </div>
      </div>
      <div>
        <pl-table
          ref="plTable"
          use-virtual
          v-loading="loading"
          :data="dataTable"
          :excess-rows="50"
          :row-height="49"
          :max-height="height"
          :row-class-name="tableRowClass"
          @selection-change="handleSelectionChange"
          :header-cell-style="{ textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
        >
          <pl-table-column v-if="!isSubmit" type="selection" width="55" fixed />
          <pl-table-column
            v-for="item in productAttrList"
            :prop="item.prokey"
            :label="item.proname"
            :width="item.width || 120"
            :key="item.ind"
          >
            <template v-if="item.required" slot="header">
              <span class="must_icon">*</span><span>{{ item.proname }}</span>
            </template>
            <template slot-scope="scope">
              <span v-if="item.type == 'errorTip'">
                <el-tooltip class="item" effect="dark" :content="scope.row[item.prokey]" placement="top-start">
                  <div class="costom_tooltip">{{ scope.row[item.prokey] }}</div>
                </el-tooltip>
              </span>
              <span v-if="item.type === 0" class="td_div">
                <el-select v-if="item.prokey === 'canCustom'" disabled v-model="scope.row[item.prokey]">
                  <el-option value="1" label="是">是</el-option>
                  <el-option value="2" label="否">否</el-option>
                </el-select>
                <el-select v-else-if="item.prokey === 'saleResType'" disabled v-model="scope.row[item.prokey]">
                  <el-option value="1" label="不低于起售量">不低于起售量</el-option>
                  <el-option value="2" label="起售量整数倍">起售量整数倍</el-option>
                </el-select>
                <span v-else :title="scope.row[item.prokey]">{{ scope.row[item.prokey] }}</span>
              </span>
              <span v-if="item.type === 1">
                <el-input
                  v-if="item.disabled"
                  v-model="scope.row[item.prokey]"
                  :disabled="true"
                  :title="scope.row[item.prokey]"
                  @keyup.native="handleMoveFocus($event)"
                ></el-input>
                <el-input
                  :key="item.prokey + '_' + scope.$index"
                  v-else-if="item.isNum"
                  v-model="scope.row[item.prokey]"
                  :title="scope.row[item.prokey]"
                  @change="(val) => {checkNum(val, item.prokey, scope.$index);}"
                  @keyup.native="handleMoveFocus($event)"
                ></el-input>
                <el-input
                  :key="item.prokey + '_' + scope.$index"
                  v-else
                  v-model="scope.row[item.prokey]"
                  :title="scope.row[item.prokey]"
                  :maxlength="item.maxlength"
                  :show-word-limit="item.maxlength ? true : false"
                  @keyup.native="handleMoveFocus($event)"
                ></el-input>
                <em
                  class="err_msg"
                  v-if=" dataTableError[scope.$index] && dataTableError[scope.$index][item.prokey]"
                  >{{ dataTableError[scope.$index][item.prokey] }}</em
                >
              </span>
              <span v-if="item.type === 2">
                <el-input
                  placeholder=""
                  :key="item.prokey + '_' + scope.$index"
                  suffix-icon="el-icon-search"
                  @focus="concatDialog(0, item.sel, item.prokey, scope.$index)"
                  v-model="scope.row[item.prokey]"
                  :title="scope.row[item.prokey]"
                >
                </el-input>
                <em
                  class="err_msg"
                  v-if="dataTableError[scope.$index] && dataTableError[scope.$index][item.prokey]"
                  >{{ dataTableError[scope.$index][item.prokey] }}</em
                >
              </span>
              <span v-if="item.type === 3">
                <template v-if="item.prokey === 'canCustom'">
                  <el-select
                    v-model="scope.row[item.prokey]"
                    placeholder="请选择"
                  >
                    <el-option value="1" label="是">是</el-option>
                    <el-option value="2" label="否">否</el-option>
                  </el-select>
                </template>
                <template v-if="item.prokey === 'saleResType'">
                  <el-select
                    v-model="scope.row[item.prokey]"
                    placeholder="请选择"
                  >
                    <el-option value="1" label="不低于起售量">不低于起售量</el-option>
                    <el-option value="2" label="起售量整数倍">起售量整数倍</el-option>
                  </el-select>
                </template>
                <template v-if="item.prokey === 'seriesUuid'">
                  <el-select
                    v-model="scope.row[item.prokey]"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in scope.row.seriesInfoVos || []"
                      :key="item.seriesUuid"
                      :label="item.series"
                      :value="item.seriesUuid"
                    />
                  </el-select>
                </template>
                <template v-if="item.prokey === 'classificationName'">
                  <el-select
                    v-if="scope.row.classificationDTOS && scope.row.classificationDTOS.length > 1"
                    v-model="scope.row.classificationUuid"
                    placeholder="请选择"
                    @change="(val) => { handleClassificationChange(val, scope.row) }"
                  >
                    <el-option
                      v-for="item in scope.row.classificationDTOS || []"
                      :key="item.uuid"
                      :label="item.classificationName"
                      :value="item.uuid"
                    />
                  </el-select>
                  <span v-else :title="scope.row[item.prokey]">{{ scope.row[item.prokey] }}</span>
                </template>
              </span>
              <span v-if="item.type === 4">
                <el-input
                  :key="item.prokey + '_' + scope.$index"
                  v-model="scope.row[item.prokey]"
                  :title="scope.row[item.prokey]"
                  :maxlength="item.maxlength"
                  :show-word-limit="item.maxlength ? true : false"
                  @keyup.native="handleMoveFocus($event)"
                  @blur="handleOtherBrandInfo(scope.$index)"
                ></el-input>
              </span>
            </template>
          </pl-table-column>
          <pl-table-column
            fixed="right"
            label="操作"
            width="100">
            <template slot-scope="scope">
              <el-button v-if="!isSubmit && !isFromSourcing" @click="handleDelete(scope.row, scope.$index)" type="text" size="small">删除</el-button>
              <el-button v-if="isSubmit" @click="handleViewPicture(scope.row)" type="text" size="small">图文</el-button>
            </template>
          </pl-table-column>
        </pl-table>
      </div>
    </el-card>
    <el-dialog
      v-dialogDrag
      :title="dialogTit"
      :visible.sync="dialogTableVisible"
      :close-on-click-modal="false"
    >
      <CategorySelect
        v-if="curConcatType == 0"
        @submitConcat="submitConcat"
        @cancelConcat="closeConcat"
      />
      <UnitSelect
        v-if="curConcatType == 3"
        @submitConcat="submitConcat"
        @cancelConcat="closeConcat"
      />
      <MaterialSelect
        v-if="curConcatType == 5"
        @submitConcat="submitConcat"
        @cancelConcat="closeConcat"
      />
    </el-dialog>
    <!-- 选择销售区域弹框 -->
    <SalesAreaDialog
      :visible.sync="dialogVisible.salesArea"
      :cityList="cityList"
      :selectCitys="selectCitys"
      @getSaleAreas="getSaleAreas"
    />
    <!-- 关联品牌弹框 -->
    <SelectBrandAndSeries
      :visible.sync="associateBrand.visible"
      @update="updateBrandAndSeriesInfo"
    />
    <!-- 系列弹框 -->
    <BatchSetSeries
      :visible.sync="setSeries.visible"
      :brandUuid="setSeries.brandUuid"
      @update="updateSeriesInfo"
    />
    <!-- 归类弹框 -->
    <BatchSetClassification
      :visible.sync="classificationVisible"
      :classificationDTOS="classificationOptions"
      @update="updateClassificationInfo"
    />
  </div>
</template>

<script>
import SkusTable from '@/components/skusTable';
import CategorySelect from '../addCode/categorySelect';
import BrandSelect from '../addCode/brandSelect';
import UnitSelect from '../addCode/unitSelect';
import MaterialSelect from '../addCode/materialSelect';
import RemoteSelect from '@/pages/commodity/components/RemoteSelect';
import SalesAreaDialog from '@/components/SalesAreaDialog';
import SelectBrandAndSeries from '../components/SelectBrandAndSeries';
import BatchSetSeries from '../components/BatchSetSeries';
import BatchSetClassification from '../components/BatchSetClassification';
import parameConfig from './constants/add';
import { OFFTIME_TYPE_OPTIONS, PRODUCT_NAME_TYPE } from './constants';
import { PRODUCT_TYPES_ENUMS } from '@/constants/commodity';
import {
  queryDetailByUuidsService, // 批量修改详情
  queryDetailBySourcingNoService, // 寻源下推详情
  queryDetailByProductNoService, // 项目转临采详情
  addSaveService, // 保存
  addSubmitService, // 提交
  batchPutOnShelvesService,
  exportAddSkuTemplateService,
} from '@/api/commodity/temporaryPurchasingGoods/temporaryPurchaseGoods';
import {
  querySalePlatAndSaleAreasService, // 获取售卖平台及销售区域
  getSeriesByBrandUuidService // 根据品牌获取系列
} from '@/api/public';
import { getOffMaxDaysService } from '@/api/commodity/temporaryPurchasingGoods/temporaryProjectGoods';
import { isResponseSuccess, createExcelByExport } from '@/utils/bizUtils';
import { getByBrandNameService } from '@api/basics/brandManage/brandManage';
import { COMMON_COMP_CONFIGS } from '../latentProduct/constants/common';

export default {
  name: 'temporaryAddCode',
  components: {
    SkusTable,
    CategorySelect,
    BrandSelect,
    UnitSelect,
    MaterialSelect,
    RemoteSelect,
    SalesAreaDialog,
    SelectBrandAndSeries,
    BatchSetSeries,
    BatchSetClassification
  },
  data () {
    return {
      tableInfo: {
        list: [],
        columns: [],
        loading: false
      },
      btnLoadings: {
        import: false,
        export: false,
      },
      isSubmit: false,
      saveBtnLoading: false,
      submitBtnLoading: false,
      cityList: [],
      selectCitys: [],
      OFFTIME_TYPE_OPTIONS,
      PRODUCT_NAME_TYPE,
      salesPlatformList: [], // 售卖平台下拉数据
      formData: {
        offTimeType: '1', // 下架类型 1-到期下架，2-永不下架，3-售完下架
        expectOffTime: '', // 预计下架时间
        salePlats: [], // 售卖平台  array
        saleAreas: [], // 销售区域  array
        saleAreasName: '', // 销售区域  array
        productNameType: '1', // 自定义商品名称 1-否，2-是
        source: '', // 来源  1-手工新增，2-询价单，3-临时项目商品
      },
      uploadData: {
        productNameType: 1
      },
      pickerOptions: {},
      dialogVisible: {
        salesArea: false,
      },
      loading: false,
      dialogTableVisible: false,
      height: 0,
      dialogTitList: [
        '关联四级类',
        '关联SPU',
        '关联品牌',
        '关联单位',
        '关联库房',
        '批量设置材质'
      ],
      dialogTit: '关联四级类',
      curConcatType: 0,
      // 表格列数据
      productAttrList: _.cloneDeep(parameConfig.temporayProductAttrList),
      // 表格数据
      dataTable: [],
      // 错误数据提示
      dataTableError: [
        {
          y: '输入错误',
          x: '格式错误'
        }
      ],
      // 当前选中的商品
      selectedProduct: [],
      // 当前选中行的索引
      selectedIndList: [],
      // 当前操作是单行，还是批量
      isMultiple: 0,
      // 如果为单行操作时，当前行的索引
      concatInd: 0,
      // 当前操作的key
      concatKey: '',
      categoryUuid: '', // spu关联筛选时，当前分类id，如果有则传，没有不传
      dialogkf: false,
      type: '', // 1代表临采新增页面过来的
      addTemporaryFlag: false, // 临采新增页面添加按钮
      temporaryInd: 0, // 新增标识
      // 根据计量单位数量小数位默认“0时为1,1时为0.1,2时为0.01,3时为0.001”
      saleMinMap: {
        0: '1',
        1: '0.1',
        2: '0.01',
        3: '0.001',
      },
      uuids: [], // 商品id集合
      associateBrand: { ...COMMON_COMP_CONFIGS },
      setSeries: {
        ...COMMON_COMP_CONFIGS,
        brandUuid: '',
      },
      classificationVisible: false,
      classificationOptions: [],
    };
  },
  created () {
    let screenHeight = document.body.clientHeight;
    this.height = screenHeight - 286;
    window.onresize = () => {
      let screenHeight = document.body.clientHeight;
      this.height = screenHeight - 286;
    };
  },
  mounted () {
    this.initPageByType()
    this.querySalePlatAndSaleAreas()
  },
  computed: {
    // 批量新增
    isFromBatchAdd () {
      return this.type == 1
    },
    // 寻源下推
    isFromSourcing () {
      return this.type == 2
    },
    // 项目转临采
    isFromProject () {
      return this.type == 3
    },
    // 用户信息
    userInfo () {
      return localStorage.userInfo ? JSON.parse(localStorage.userInfo) : {}
    },
    // 销售区域是否必填
    saleAreasIsRequired () {
      const { salePlats } = this.formData;
      return !(salePlats.length == 1 && salePlats.includes('marketing_saleplat_swan'))
    }
  },
  beforeRouteEnter (to, from, next) {
    next((vm) => {
      if (from.name == 'imageTextManage') {
        // temporayUuids
        vm.uuids = JSON.parse(sessionStorage.temporayUuids)
        vm.isSubmit = true;
        vm.queryDetailByUuids()
      } else {
        vm.isSubmit = false;
        sessionStorage.removeItem('temporayUuids')
      }
    });
  },
  methods: {
    // 更新品牌系列信息
    updateBrandAndSeriesInfo (info) {
      this.dataChange(info)
    },
    // 更新系列信息
    updateSeriesInfo (info) {
      this.dataChange(info)
    },
    // 更新归类信息
    updateClassificationInfo (info) {
      this.dataChange(info)
    },
    // 系列
    handleSeries (selection) {
      const brandUuid = selection[0].brandUuid
      if (!brandUuid) return this.$message.warning('品牌Id不能为空')
      const isAllSameBrand = selection.every(item => item.brandUuid == brandUuid)
      if (!isAllSameBrand) return this.$message.warning('请勾选相同品牌的商品进行系列设置')
      this.setSeries.brandUuid = brandUuid
      this.setSeries.open()
    },
    // 归类名称
    handleSetClassification (selection) {
      const categoryUuid = selection[0].categoryUuid
      if (!categoryUuid) return this.$message.warning('分类不能为空')
      const isAllSame = selection.every(item => item.categoryUuid == categoryUuid)
      if (!isAllSame) return this.$message.warning('请勾选相同分类的商品进行归类设置')
      this.classificationOptions = selection[0].classificationDTOS
      console.log(this.classificationOptions)
      this.classificationVisible = true
    },
    // 一键勾选相同品牌
    handleCheckSameBrand () {
      if (!this.selectedProduct.length || this.selectedProduct.length == 0) {
        return this.$message.warning('请勾选商品后进行操作');
      }
      const brandUuid = this.selectedProduct[0].brandUuid
      const isAllSameBrand = this.selectedProduct.every(item => item.brandUuid == brandUuid)
      if (!isAllSameBrand) return this.$message.warning('不支持勾选多个品牌进行设置')
      this.dataTable.forEach(item => {
        if (item.brandUuid != brandUuid) return
        this.$nextTick(() => {
          this.$refs.plTable.$refs.singleTable.toggleRowSelection(item, true)
        })
      })
    },
    // 一键勾选相同品类
    handleCheckSameCategory () {
      if (!this.selectedProduct.length || this.selectedProduct.length == 0) {
        return this.$message.warning('请勾选商品后进行操作');
      }
      const categoryUuid = this.selectedProduct[0].categoryUuid
      const isAllSame = this.selectedProduct.every(item => item.categoryUuid == categoryUuid)
      if (!isAllSame) return this.$message.warning('不支持勾选多个分类进行设置')
      this.dataTable.forEach(item => {
        if (item.categoryUuid != categoryUuid) return
        this.$nextTick(() => {
          this.$refs.plTable.$refs.singleTable.toggleRowSelection(item, true)
        })
      })
    },
    // 归类选择
    handleClassificationChange (val, row) {
      const selectItem = row.classificationDTOS.find(item => item.uuid == val)
      const {
        classificationName,
        uuid,
        taxCateName,
        taxCateNo,
        taxRate
      } = selectItem
      row.classificationName = classificationName
      row.classificationUuid = uuid
      row.taxCateName = taxCateName
      row.taxCateNo = taxCateNo
      row.taxRate = taxRate
    },
    // 初始化页面数据
    initPageByType () {
      // type: 1-手工新增，2-询价单，3-临时项目商品
      const { type, sourceType } = this.$route.query;
      this.type = type;
      // 批量新增
      if (this.type == 1) {
        this.formData.source = this.type;
        this.addTemporaryFlag = true;
        this.addButton()
        this.handleProductNameTypeSelect(1)
      }
      // 寻源
      if (this.type == 2) {
        this.productAttrList = _.cloneDeep(parameConfig.productAttrList);
        this.queryDetailBySourcingNo(this.$route.query.sourceBillId)
      }
      // 项目转临采
      if (this.type == 3) {
        this.queryDetailByProductNo(JSON.parse(sessionStorage.getItem('translate-temporary-goods-uuids')));
      }
      // 草稿
      if (this.type == 4) {
        if (sourceType == 2) {
          this.type = 2
          this.productAttrList = _.cloneDeep(parameConfig.productAttrList);
        }
        this.uuids = this.$route.params.uuids
        this.queryDetailByUuids()
      }
      if (this.isSubmit) {
        this.productAttrList.forEach(item => {
          item.type = 0
        })
      }
      this.setDatePickerOptions()
    },
    // 设置时间选择器options
    async setDatePickerOptions () {
      const res = await getOffMaxDaysService('.project_goods_add');
      if (!res?.retData) return false;
      const maxDays = res.retData - 1;
      this.pickerOptions = {
        disabledDate: (time) => {
          const MAX_DAYS_LIMIT = maxDays * 24 * 3600 * 1000;
          const isSmaller = time.getTime() <= new Date().getTime();
          const isMoreThan = time.getTime() > new Date().getTime() + MAX_DAYS_LIMIT;
          return isSmaller || isMoreThan;
        }
      }
    },
    // 立即上架
    async batchPutOnShelves () {
      const data = {
        uuids: this.uuids,
        operType: 1,
      }
      const res = await batchPutOnShelvesService(data, state => { this.submitBtnLoading = state });
      if (res) {
        this.$message.success('操作成功')
        this.hanldeGoBack()
      }
    },
    // 获取售卖平台及销售区域
    async querySalePlatAndSaleAreas () {
      const data = {};
      const res = await querySalePlatAndSaleAreasService(data, state => { this.loading = state });
      if (res) {
        const { retData } = res;
        this.cityList = retData.saleAreaList || [];
        this.salesPlatformList = retData.salePlatList || [];
      }
    },
    // 获取系列
    async getSeriesByBrandUuid (brandUuid) {
      const res = await getSeriesByBrandUuidService({ brandUuid }, state => { this.loading = state });
      if (res) {
        const { retData } = res;
        return retData;
      }
    },
    initFormData (data) {
      if (!data) {
        return;
      }
      this.dataTable.forEach((item, index) => {
        item.ind = index;
      })
      const {
        offTimeType, // 下架类型 1-到期下架，2-永不下架，3-售完下架
        expectOffTime, // 预计下架时间
        salePlatCodes, // 售卖平台  array
        saleAreaCodes, // 销售区域  array
        saleAreaStr, // 销售区域  array
        productNameType, // 自定义商品名称 1-否，2-是
        source
      } = data;
      this.formData = {
        offTimeType: offTimeType || '1', // 下架类型 1-到期下架，2-永不下架，3-售完下架
        expectOffTime,
        salePlats: salePlatCodes || [],
        saleAreas: saleAreaCodes || [],
        saleAreasName: saleAreaStr,
        productNameType: productNameType || '1', // 自定义商品名称 1-否，2-是
        source, // 来源  1-手工新增，2-询价单，3-临时项目商品
      }
      this.handleProductNameTypeSelect(this.formData.productNameType)
    },
    // 批量新增获取详情
    async queryDetailByUuids () {
      const { retData } = await queryDetailByUuidsService(this.uuids, state => { this.loading = state });
      if (retData) {
        this.dataTable = retData;
        this.initFormData(retData[0])
      }
    },
    // 寻源下推获取详情
    async queryDetailBySourcingNo (orderNo) {
      const data = {
        nowPage: 1,
        pageShow: 1000,
        searchParam: JSON.stringify([
          { name: 'orderNo', value: orderNo.toString() }
        ])
      };
      const { retData } = await queryDetailBySourcingNoService(data, state => { this.loading = state });
      if (retData) {
        this.dataTable = retData.results || [];
        // this.productDataFormat(retData.results);
        this.initFormData(retData.results[0])
      }
    },
    // 项目转临采获取详情
    async queryDetailByProductNo (data) {
      const { retData } = await queryDetailByProductNoService(data, state => { this.loading = state });
      if (retData) {
        this.dataTable = retData
        this.initFormData(retData[0])
      }
    },
    // 保存
    async handleSaveAction () {
      if (this.dataTable.length == 0) {
        return this.$message.warning('列表数据不能为空')
      }
      const data = {
        ...this.formData,
        dataList: this.dataTable
      };
      const res = await addSaveService(data, state => { this.saveBtnLoading = state });
      if (res) {
        this.$message.success('保存成功');
        this.dataTable = res.retData;
        this.dataTable.forEach((item, index) => {
          item.ind = index;
        })
      }
    },
    // 提交
    async handleSubmitAction () {
      if (!this.dataTable.length) {
        return this.$message.error('列表数据不能为空');
      }
      const data = {
        ...this.formData,
        dataList: this.dataTable
      };
      const res = await addSubmitService(data, state => { this.submitBtnLoading = state });
      if (res) {
        if (res.retData && res.retData.hasErrorMsg) {
          this.$alert('存在异常原因，无法提交单据，请在详情页中查看具体原因', '提交错误提示', {
            confirmButtonText: '确定',
            type: 'warning',
          });
          if (this.productAttrList.every(item => item.prokey != 'errorMsg')) {
            this.productAttrList.unshift({
              prokey: 'errorMsg',
              proname: '异常原因',
              type: 'errorTip',
              width: 100
            })
          }
          this.dataTable = res.retData.data;
          this.dataTable.forEach((item, index) => {
            item.ind = index;
          })
        } else {
          this.$message.success('提交成功,请继续完善商品图文后上架')
          this.isSubmit = true;
          this.uuids = res.retData?.data;
          sessionStorage.setItem('temporayUuids', JSON.stringify(res.retData?.data))
          this.productAttrList.forEach(item => {
            item.type = 0
          })
          this.queryDetailByUuids()
        }
      }
    },

    async handleOtherBrandInfo (index) {
      if (!this.dataTable[index].otherBrandName) {
        return;
      }
      this.dataTable[index].otherBrandName = this.dataTable[index].otherBrandName.trim();
      if (!this.dataTable[index].otherBrandName) {
        return;
      }
      const res = await getByBrandNameService(
        this.dataTable[index].otherBrandName,
        state => { this.loading = state }
      );
      const ret = res?.retData
      if (ret) {
        this.dataTable[index].brandName = ret.brandName;
        this.dataTable[index].brandUuid = ret.uuid;
        this.dataTable[index].otherBrandName = '';
      }
    },

    handleSubmit () {
      this.$refs.tempForm.validate((valid) => {
        if (valid) {
          this.handleSubmitAction()
        }
      })
    },
    // 导出模板
    async handleExportTemplate () {
      const data = {
        source: this.formData.source,
        productNameType: this.formData.productNameType,
        uuids: this.dataTable.length ? this.dataTable.map(item => item.uuid) : []
      }
      const loadingFn = state => { this.btnLoadings.export = state };
      const res = await exportAddSkuTemplateService(data, loadingFn);
      createExcelByExport({ res, excelTitle: '线索商品新增模板' });
    },
    beforeFileUpload (file) {
      // this.baseTableData = [];
      this.btnLoadings.import = true;
    },
    uploadSuccess (res) {
      this.btnLoadings.import = false;
      if (isResponseSuccess(res)) {
        this.$message.success('导入成功')
        this.dataTable = res.retData;
        this.dataTable.forEach((item, index) => {
          item.ind = index;
        })
      } else {
        this.$message.error(res.retMessage || '模板导入异常');
      }
    },
    uploadError (file) {
      this.btnLoadings.import = false;
      this.$message.error('模板导入异常');
    },
    // 选择下架类型
    handleOffTimeTypeSelect (val) {
      if (val !== 1) {
        this.formData.expectOffTime = '';
      }
    },
    // 选择自定义商品名称
    handleProductNameTypeSelect (val) {
      this.uploadData = {
        productNameType: val,
        source: this.formData.source,
        uuids: this.dataTable.length ? this.dataTable.map(item => item.uuid) : []
      }
      if (val == 1) {
        this.productAttrList.forEach(item => {
          if (item.prokey == 'productName') {
            item.type = 0;
          }
          if (item.prokey == 'mainCategoryName') {
            item.required = true;
          }
        })
      }
      if (val == 2) {
        this.productAttrList.forEach(item => {
          if (item.prokey == 'productName') {
            item.type = 1
          }
          if (item.prokey == 'mainCategoryName') {
            item.required = false;
          }
        })
      }
    },
    // 显示销售区域弹框
    handleShowCityDialog () {
      this.dialogVisible.salesArea = true;
      this.selectCitys = this.formData.saleAreas;
    },
    // 删除
    handleDelete (row, index) {
      this.$confirm('确定要删除吗？', '删除', {
        type: 'warning',
      }).then(() => {
        this.dataTable.splice(index, 1)
      }).catch(() => {});
    },
    // 图文
    handleViewPicture (row) {
      this.$router.push({
        name: 'imageTextManage',
        query: {
          skuId: row.uuid,
          skuNo: row.skuNo,
          productType: PRODUCT_TYPES_ENUMS.TEMP,
          // fromName: this.$route.name,
        }
      });
    },
    // 获取
    getSaleAreas (data) {
      this.formData.saleAreasName = this.cityList.filter(item => data.includes(item.areaCode)).map(item => item.shortName).join(',')
      this.formData.saleAreas = data;
    },
    /* 临采商品新增页面逻辑 */
    addButton () {
      this.dataTable.push({
        ind: this.temporaryInd++,
        skuNo: '',
        categoryName: '',
        classificationName: '',
        taxRate: '',
        brandName: '',
        seriesUuid: '',
        seriesInfoVos: [],
        productName: '',
        material: '',
        mainCategoryName: '',
        specModel: '',
        unitName: '',
        edge1: '',
        edge2: '',
        edge3: '',
        volume: '',
        weight: '',
        canCustom: '2',
        note: '',
        purchasePrice: '',
        costPrice: '',
        sellPrice: '',
        operName: this.userInfo?.userName,
        operDeptName: this.userInfo?.hrDepartmentName,
        createOpeTime: '',
        saleMin: '',
        saleResType: '1',
        arrivalPeriod: '',
      });
    },
    tableRowClass () {
      return 'tem_row';
    },
    // 表格勾选
    handleSelectionChange (val) {
      this.selectedProduct = val;
    },
    /**
     *isMultiple ：multiple时为true批量操作，其它单品
     *type: 0分类，1spu,2品牌，3单位，4仓库
     *itemkey:当前操作的key,仓库多个时用
     *curInd:单品时的索引
     * **/
    concatDialog (isMultiple, type, itemkey, curInd) {
      this.isMultiple = isMultiple;
      if (isMultiple && !this.selectedProduct.length) {
        return this.$Message.error('请选择要关联的商品！');
      }
      if (!isMultiple) {
        this.concatInd = curInd;
        // eslint-disable-next-line no-unused-expressions
        type == 1 ? (this.categoryUuid = this.dataTable[curInd].categoryUuid ? this.dataTable[curInd].categoryUuid : '') : false;
      }
      if (itemkey) {
        this.concatKey = itemkey
      }
      this.curConcatType = type;
      if (type == '2') { // 关联品牌
        return this.associateBrand.open()
      }
      if (type == 'series') { // 设置系列
        return this.handleSeries(this.selectedProduct)
      }
      if (type == 9) { // 设置归类名称
        return this.handleSetClassification(this.selectedProduct)
      }
      this.dialogTit = this.dialogTitList[Number(type)];
      this.dialogTableVisible = true;
    },
    // 品类、品牌、单位选择回调
    submitConcat (val) {
      this.dialogTableVisible = false;
      this.dataChange(val);
    },
    dataChange (valObj) {
      console.log('valObj: ' + JSON.stringify(valObj));
      let curIndList = null;
      if (this.isMultiple) {
        curIndList = this.selectedProduct.map(item => item.ind);
      } else {
        curIndList = [this.concatInd];
      }
      if (this.curConcatType === 3) {
        // 选择计量单位带出最小起售量
        this.dataTable.forEach((item, index) => {
          if (curIndList.includes(item.ind)) {
            if (!item.saleMin || Object.values(this.saleMinMap).includes(item.saleMin)) {
              item.saleMin = this.saleMinMap[valObj.decimalPlaces];
            }
            Object.assign(this.dataTable[index], valObj);
          }
        })
      } else if (this.curConcatType === 0) {
        // classificationDTOS
        this.dataTable.forEach((item, index) => {
          if (curIndList.includes(item.ind)) {
            const classificationObj = {
              ...valObj,
              uuid: valObj.classificationUuid
            }
            item.classificationDTOS = [classificationObj];
            Object.assign(this.dataTable[index], valObj);
          }
        })
      } else {
        for (let i = 0; i < curIndList.length; i++) {
          let curKk = curIndList[i];
          Object.assign(this.dataTable[curKk], valObj);
        }
      }
    },
    // 关闭弹框
    closeConcat () {
      this.dialogTableVisible = false;
    },
    hanldeGoBack () {
      this.$router.go(-1)
    },
    computedVolume (edge1, edge2, edge3) {
      if (edge1 && edge2 && edge3) {
        let val = (edge1 * edge2 * edge3) / 1000000;

        val = Number(val).toFixed(6);
        if (val <= 0) {
          val = 0.000001;
        }
        return val;
      } else {
        return '';
      }
    },
    checkNum (tVal, key, ind) {
      let curVal = tVal.replace(/[^0-9.]/g, '');
      if (!curVal) {
        this.dataTable[ind][key] = curVal;
        return;
      }
      if (
        key === 'purchasePrice' ||
        key === 'costPrice'
        // key === 'sellPrice'
      ) {
        curVal = this.toFixedFn(Number(curVal), 3);
      } else {
        curVal = this.toFixedFn(Number(curVal), 2);
      }
      this.dataTable[ind][key] = Number(curVal);
      if (key === 'edge1' || key === 'edge2' || key === 'edge3') {
        this.dataTable[ind].volume = this.computedVolume(
          this.dataTable[ind].edge1,
          this.dataTable[ind].edge2,
          this.dataTable[ind].edge3
        );
      }
    },
    toFixedFn (num, toNum) {
      let def = 100;
      if (toNum == 3) {
        def = 1000;
      }
      if (toNum == 6) {
        def = 1000000;
      }
      if (num > 0) {
        return Math.round(num * def) / def;
      }
      return 0;
    },
    handleMoveFocus (event) {
      let curel = document.activeElement; // 当前input元素
      let curtTd = curel.parentElement.parentElement.parentElement.parentElement;
      let curcellIndex = curtTd.cellIndex; // 当前元素行单元格索引
      let curtTr = curtTd.parentElement; // 当前tr
      let curRowIndex = curtTr.sectionRowIndex; // 当前元素行的索引；
      let curtbody = curtTr.parentElement.children; // 当前tbody内容的整个表单
      // 向上
      if (event.keyCode == 38) {
        if (curRowIndex - 1 >= 0) {
          curtbody[curRowIndex - 1].children[curcellIndex].querySelector('.el-input__inner').focus()
        }
      }
      // 向下
      if (event.keyCode == 40) {
        if (curRowIndex + 1 !== curtbody.length) {
          curtbody[curRowIndex + 1].children[curcellIndex].querySelector('.el-input__inner').focus()
        }
      }
      // 向右
      if (event.keyCode === 39) {
        const rightInput = curtTr.children[curcellIndex + 1].querySelector('.el-input__inner');
        if (rightInput) {
          rightInput.focus()
        }
      }
      // 向左
      if (event.keyCode === 37) {
        const leftInput = curtTr.children[curcellIndex - 1].querySelector('.el-input__inner');
        if (leftInput) {
          leftInput.focus()
        }
      }
    },
  },
  directives: {
    dialogDrag: {
      bind (el, binding, vnode, oldVnode) {
        const dialogHeaderEl = el.querySelector('.el-dialog__header');
        const dragDom = el.querySelector('.el-dialog');
        dialogHeaderEl.style.cssText += ';cursor:move;';
        dragDom.style.cssText += ';top:0px;';
        // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
        const sty = (function () {
          if (window.document.currentStyle) {
            return (dom, attr) => dom.currentStyle[attr];
          } else {
            return (dom, attr) => getComputedStyle(dom, false)[attr];
          }
        })();
        dialogHeaderEl.onmousedown = (e) => {
          // 鼠标按下，计算当前元素距离可视区的距离
          const disX = e.clientX - dialogHeaderEl.offsetLeft;
          const disY = e.clientY - dialogHeaderEl.offsetTop;

          const screenWidth = document.body.clientWidth; // body当前宽度
          const screenHeight = document.documentElement.clientHeight; // 可见区域高度(应为body高度，可某些环境下无法获取)

          const dragDomWidth = dragDom.offsetWidth; // 对话框宽度
          const dragDomheight = dragDom.offsetHeight; // 对话框高度

          const minDragDomLeft = dragDom.offsetLeft;
          const maxDragDomLeft =
            screenWidth - dragDom.offsetLeft - dragDomWidth;

          const minDragDomTop = dragDom.offsetTop;
          const maxDragDomTop =
            screenHeight - dragDom.offsetTop - dragDomheight;
          // 获取到的值带px 正则匹配替换
          let styL = sty(dragDom, 'left');
          let styT = sty(dragDom, 'top');

          // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
          if (styL.includes('%')) {
            // eslint-disable-next-line no-useless-escape
            styL = +document.body.clientWidth * (+styL.replace(/\%/g, '') / 100);
            // eslint-disable-next-line no-useless-escape
            styT = +document.body.clientHeight * (+styT.replace(/\%/g, '') / 100);
          } else {
            styL = +styL.replace(/\px/g, '');
            styT = +styT.replace(/\px/g, '');
          }

          document.onmousemove = function (e) {
            // 通过事件委托，计算移动的距离
            let left = e.clientX - disX;
            let top = e.clientY - disY;

            // 边界处理
            if (-left > minDragDomLeft) {
              left = -minDragDomLeft;
            } else if (left > maxDragDomLeft) {
              left = maxDragDomLeft;
            }

            if (-top > minDragDomTop) {
              top = -minDragDomTop;
            } else if (top > maxDragDomTop) {
              top = maxDragDomTop;
            }

            // 移动当前元素
            dragDom.style.cssText += `;left:${left + styL}px;top:${top + styT}px;`;
          };

          document.onmouseup = function (e) {
            document.onmousemove = null;
            document.onmouseup = null;
          };
        };
      }
    }
  }
};
</script>

<style scoped>
.card-title {
  margin-bottom: 3px;
}
.operating-area {
  float: right;
}
.srm_table_head {
  text-align: center;
}
.must_icon {
  color: red;
  margin: 0 5px;
}

.err_msg {
  position: absolute;
  left: 10px;
  bottom: -4px;
  font-style: normal;
  color: red;
}

.kf_radio .kf_radio_btn {
  margin: 10px 20px;
}
.tem_page >>> .el-table .pl-table-beyond {
  position: static;
}
.sale-area-input {
  width: 220px;
}
.el-select, .el-input {
  width: 90%;
}
.import-file {
  display: inline-block;
  margin-left: 10px;
}
.tip {
  display: inline-block;
  color: red;
  font-size: 14px;
}
</style>
